# -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 15:42:15 2013

@author: chico
"""


import sys
from PySide import QtCore, QtGui, QtWebKit
from libatomism import *

from simpletreemodel import *
import functools
from PopUpBox import *

class ParamTreeModel(TreeModel):
    def __init__(self, data, parent=None):
        super(TreeModel, self).__init__(parent)

        self.rootItem = TreeItem(("Id","Unit","Value","Comment"))
        self.addDataChildren(data, self.rootItem )
        self.filter="msParam"
    
    def addDataChildren(self,data,parent):
        listchildren = data.getChildren()
        for child in listchildren:
            try:
                textData=[]
                textData.append(child.getId())
                textData.append(child.getUnit())
                textData.append(child.getValue())
                textData.append(child.getAbstract())
                item=TreeItem(textData,parent)
                item.setRawdata(child)
                parent.appendChild(item)
                self.addDataChildren(child,parent.child(parent.childCount()-1))
            except:
                a=0
        return data
        
        
class uiUnitsManager(QtGui.QWidget):
    
    def __init__(self,data,mainwindows):
        super(uiUnitsManager, self).__init__()
        
        self.data = data
        self.initUI()
        if(not data.isDerivedFrom("msUnitsManager")):
            raise Exception("uiUnitsManager can be instanciated only "+
                            "with a msUnitsManager derived object.")
            
    def initUI(self):
        
        mainbox  =  QtGui.QVBoxLayout()
        
        """ First create the Units group box
        """
        self.Units  =  QtGui.QGroupBox("msUnitsManager")
        vbox        =  QtGui.QVBoxLayout()
        
        targets     = [ "Energy","Time","Length","Mass","Angle" ]
        targetsType = [ unitTypeVar.vEnergy, unitTypeVar.vTime,
                        unitTypeVar.vLength, unitTypeVar.vMass, 
                        unitTypeVar.vAngle ]
        
        self.gridbox = QtGui.QGridLayout()
        i=0
        for unit in targets:
            self.gridbox.addWidget( QtGui.QLabel(unit),i+1,1)
            combobox = QtGui.QComboBox()
            listUnits = msUnitsManager.listUnitsAvailable(targetsType[i])
            for j in listUnits:
                combobox.addItem(j)
   
            self.gridbox.addWidget(combobox,i+1,2)
            i = i+1
            
        updateUnitsButton = QtGui.QPushButton("update")
        self.gridbox.addWidget(updateUnitsButton,i+1,2)
        self.Units.setLayout(self.gridbox)  
        
        mainbox.addWidget(self.Units)
        self.setLayout(mainbox)
        #self.setMinimumSize(350,250)
        #self.setMaximumSize(350,250)
        #self.setSizePolicy(QtGui.QSizePolicy.fixed,QtGui.QSizePolicy.fixed)
        
        self.setMaximumHeight(250)
       
class uiParamsManager(QtGui.QWidget):
    
    def __init__(self,data,mainwindows):
        super(uiParamsManager, self).__init__()
        
        if(not data.isDerivedFrom("msParamsManager")):
            ret=QtGui.QMessageBox.critical(self,'An exception occured',
                                           "uiParamsManager can be instanciated only "+
                                           "with a msParamsManager derived object." , 
                                           QtGui.QMessageBox.Yes,
                                           QtGui.QMessageBox.Yes) 
            raise Exception("uiParamsManager can be instanciated only "+
                            "with a msParamsManager derived object.")
        self.data = data
        try:
            self.initUI()
        except:
            ret=QtGui.QMessageBox.critical(self,'An exception occured',
                                           'Exception:'+str(sys.exc_info()) , 
                                           QtGui.QMessageBox.Yes,
                                           QtGui.QMessageBox.Yes) 
    def initUI(self):
        
        mainbox  =  QtGui.QVBoxLayout()
        
        self.Parameters = QtGui.QGroupBox("msParamsManager")
        
        self.ParamList = QtGui.QTreeView()
        
        model = ParamTreeModel(self.data)
        self.ParamList.setModel(model)
        
        vbox  =  QtGui.QVBoxLayout(self)
        vbox.addWidget(self.ParamList)
        
        self.frame = QtGui.QFrame()
        hbox       =  QtGui.QHBoxLayout()  
        updateParamButton = QtGui.QPushButton("update")
        hbox.addWidget(updateParamButton)
        self.frame.setLayout(hbox)
        
        vbox.addWidget(self.frame)
        self.Parameters.setLayout(vbox)
        
        mainbox.addWidget(self.Parameters)
        self.setLayout(mainbox)
        
        #self.setMinimumSize(350,250)
        #self.setMaximumSize(350,250)
        self.setMaximumHeight(250)
 
    
      

class uiParser(QtGui.QWidget):
    
    def __init__(self,data,mainwindows):
        super(uiParser, self).__init__()
        
        self.data = data
        if(not data.isDerivedFrom("msParser")):
            raise Exception("uiParser can be instanciated only "+
                            "with a msParser derived object.")
        self.mainwindows=mainwindows
        self.initUI()
            
    def initUI(self):
        
        mainbox  =  QtGui.QVBoxLayout()
        
        """ First create the Units group box
        """
        self.group  =  QtGui.QGroupBox("msParser")
        vbox        =  QtGui.QVBoxLayout()
        
        self.expression = QtGui.QTextEdit()
        self.expression.setText(self.data.getExpression())
        
        vbox.addWidget(QtGui.QLabel("expression:")) 
        vbox.addWidget(self.expression)    
        self.update = QtGui.QPushButton("update")
        vbox.addWidget(self.update)  
        
        self.update.clicked.connect(self.updateExpression)
        self.group.setLayout(vbox)
        mainbox.addWidget(self.group)
        self.setLayout(mainbox)
        self.setMinimumSize(400,200)
        self.setMaximumSize(400,200)
    
    def updateExpression(self):
        
        self.data.setExpression(str(self.expression.toPlainText()))
        self.mainwindows.clickTreeView()
  

class uiUnit(QtGui.QWidget):
    
    def __init__(self,data,mainwindows):
        super(uiUnit, self).__init__()
        self.data = data
        self.initUI()
        
    def initUI(self):
        
        self.vbox = QtGui.QVBoxLayout()
        
        self.vbox.addWidget(QtGui.QLabel("Type var"),1,1)
        
        self.listVarType =  QtGui.QComboBox()
        for item in inspect.getmembers(unitTypeVar)[-1][1].values():
            self.listVarType.addItem(str(item))
        self.vbox.addWidget(self.listVarType)
    
        self.listVarValue =  QtGui.QComboBox()
        self.vbox.addWidget(self.listVarValue)
              
        self.listVarType.currentIndexChanged.connect(self.updatelistVarValues)
        
        self.setLayout(self.vbox)
        
    def updatelistVarValues(self):
            
        listUnits = msUnitsManager.listUnitsAvailable(inspect.getmembers(unitTypeVar)[-1][1].values()[self.listVarType.currentIndex()])
        self.listVarValue.clear()
        for j in listUnits:
               self.listVarValue.addItem(j)
              
    
class uiSetCoordinate(QtGui.QWidget):
    
    def __init__(self,data,methodupdate):
        super(uiSetCoordinate, self).__init__()
        self.data = data
        self.methodUpdate = methodupdate
        self.initUI()
        
    def initUI(self):
        
        vbox = QtGui.QGridLayout()
        
        vbox.addWidget(QtGui.QLabel("Minimum"),1,1)
        vbox.addWidget(QtGui.QLabel("Maximum"),2,1)        
        vbox.addWidget(QtGui.QLabel("Derivation step"),3,1)
        vbox.addWidget(QtGui.QLabel("Integration step"),4,1)
        
        self.min=QtGui.QLineEdit()
        self.max=QtGui.QLineEdit()
        self.dq=QtGui.QLineEdit()
        self.Dq=QtGui.QLineEdit()
        
        self.min.setText(str(self.data.Min))        
        self.max.setText(str(self.data.Max))             
        self.dq.setText(str(self.data.dq))                 
        self.Dq.setText(str(self.data.Dq))
        
        vbox.addWidget(self.min,1,2)
        vbox.addWidget(self.max,2,2)        
        vbox.addWidget(self.dq,3,2)
        vbox.addWidget(self.Dq,4,2)
        
        okbtn=QtGui.QPushButton("update")
        okbtn.clicked.connect(self.execute)
        self.unitWidget = uiUnit(self.data,0)
        vbox.addWidget(self.unitWidget,5,2)
        vbox.addWidget(okbtn,6,2)
        self.setLayout(vbox)
    
    def execute(self):
        self.data.Min = float(self.min.text())
        self.data.Max = float(self.max.text())
        self.data.dq = float(self.dq.text())
        self.data.Dq = float(self.Dq.text())
        self.data.setUnit(str(self.unitWidget.listVarValue.currentText()))
        self.methodUpdate()
                        
    